import React, {TargetedEvent} from "preact/compat";
import {CSSProperties, useState} from "react";

const styles: CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    position: 'fixed',
    zIndex: 100,
    width: '30%',
    height: '500px',
    top: '5%',
    left: '40%',
    right: 0,
    justifyContent: 'center',
    background: 'white'
}

const NewExam: React.FC<{ cancel: () => void }> = ({cancel}) => {
    const [q, setQ] = useState<string>('');
    const [a, setA] = useState<string>('');
    const [v, setV] = useState<string>('');
    const inputQ = (e: TargetedEvent<HTMLInputElement, Event>) => {
        if (!e.target) {
            return;
        }
        // @ts-ignore
        setQ(e.target.value.replace(/ \n\t\r/g, ''));
    }
    const inputA = (e: TargetedEvent<HTMLTextAreaElement, Event>) => {
        if (!e.target) {
            return;
        }
        // @ts-ignore
        setA(e.target.value.replace(/ \t\r/g, ''));
    }
    const inputV = (e: TargetedEvent<HTMLTextAreaElement, Event>) => {
        if (!e.target) {
            return;
        }
        // @ts-ignore
        setV(e.target.value.replace(/ \t\r/g, ''));
    }
    const saveQuestion = async () => {
        if (q === '' || a === '') {
            alert("问题/答案为空")
            return;
        }
        const resp = await fetch(`/api/exams`, {
            method: 'POST',
            body: JSON.stringify({question: q, answer: a, memos: v})
        });
        const data = await resp.json();
        alert(data.status);
        setQ("");
        setA("");
        setV("");
        cancel();
    }
    return <div style={styles}>
        <p style={{display: 'flex'}}>问题：<input style={{width: '300px'}} value={q} onChange={inputQ}/></p>
        <p style={{display: 'flex'}}>答案：<textarea style={{width: '300px', height: '100px', resize: 'none'}} value={a}
                                                    onChange={inputA}></textarea></p>
        <p style={{display: 'flex'}}>解析：<textarea style={{width: '300px', height: '100px', resize: 'none'}} value={v}
                                                    onChange={inputV}></textarea></p>
        <p style={{display: 'flex', justifyContent: 'center'}}>
            <button style={{width: '100%', height: '50px'}} onClick={saveQuestion}>保存</button>
        </p>
        <p style={{display: 'flex', justifyContent: 'center'}}>
            <button style={{width: '100%', height: '50px'}} onClick={cancel}>取消</button>
        </p>
    </div>
}
export {NewExam};